package org.yeruyi.common.fragment;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.support.annotation.MainThread;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import org.yeruyi.common.activity.RoyBaseActivity;
import org.yeruyi.common.exception.NoPatchException;
import org.yeruyi.common.presenter.RoyBasePresenter;
import org.yeruyi.common.inter.RoyBaseView;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Author：yeruyi
 * Date：2017/3/12
 * Version：v1.0
 * Note:
 * <p>
 * 2017年03月12日 简化代码创建对象
 * 2017年11月14日 因为部分需求在oncreate时候需要获取savedInstanceState，需要做处理。
 * 2017年11月21日 修改部分msgDialog接口
 */

public abstract class RoyBaseFragment extends Fragment implements RoyBaseView {

    protected static final String TAG = "[RoyBaseFragment]";

    public RoyBasePresenter mPresenter;

    Unbinder unbinder;

    /**
     * 对状态做出处理，常规这里是不做操作的，部分需要
     *
     * @param savedInstanceState 状态
     */
    protected void initWithSaveInstanceState(Bundle savedInstanceState) {
    }

    /**
     * 布局ID
     *
     * @return layoutId
     */
    protected abstract int getLayoutId();

    /**
     * 对Presenter进行初始化
     *
     * @return layoutId
     */
    protected abstract RoyBasePresenter initPresenter();

    /**
     * 处理ViewEvent
     */
    protected abstract void initViewEvent();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        initButterKnife(view, savedInstanceState);
        // 暴露savedInstanceState参数
        initWithSaveInstanceState(savedInstanceState);
        // 初始化Presenter
        mPresenter = initPresenter();
        if (mPresenter != null) {
            mPresenter.onViewInit();
        }
        // 暴露对外的操作方法
        initViewEvent();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (mPresenter != null)
            mPresenter.onViewReady(getActivity().getIntent());
    }

    /**
     * destroy自定义方法，回调presneter.destroy方法
     */
    protected void destroy() {
        if (mPresenter != null) {
            mPresenter.destroy();
        }
    }


    /**
     * 初始化butterknife组件
     *
     * @param view               view
     * @param savedInstanceState 状态
     */
    private void initButterKnife(View view, Bundle savedInstanceState) {
        unbinder = ButterKnife.bind(this, view);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        destroy();
    }

    @Override
    public boolean showProcessDialog(String msg) {
        if (getActivity() instanceof RoyBaseActivity)
            return ((RoyBaseActivity) getActivity()).showProcessDialog(msg);
        return false;
    }

    @Override
    public boolean dismissProcessDialog() {
        if (getActivity() instanceof RoyBaseActivity)
            return ((RoyBaseActivity) getActivity()).dismissProcessDialog();
        Log.e(TAG, "dismissProcessDiaglog: [父类对象异常]");
        return false;
    }

    @Override
    public void finishActivity() {
        getActivity().finish();
    }

    @Override
    public Context getActivityContext() {
        return getContext();
    }

    @Override
    public void showToast(String msg) {
        ((RoyBaseActivity) getActivity()).showToast(msg);
    }

    @Override
    public void finishActivityWithResultIntent(int result, Intent intent) {
        getActivity().setResult(result, intent);
        finishActivity();
    }


    @Override
    public void finishActivityWithResult(int result) {
        getActivity().setResult(result);
    }

    @Override
    public void skipActivityForResult(Intent intent, int requestCode) {
        ((RoyBaseActivity) getActivity()).skipActivityForResult(intent, requestCode);
    }

    @Override
    public void skipActivityWithIntent(Intent intent, boolean isFinished) {
        getActivity().startActivity(intent);
        if (isFinished) {
            getActivity().finish();
        }
    }

    @Override
    public void registerReceiverFromPresenter(BroadcastReceiver receiver, IntentFilter intentFilter) {
        getActivityContext().registerReceiver(receiver, intentFilter);
    }

    @Override
    public void unregisterReceiverFromPresenter(BroadcastReceiver receiver) {
        getActivityContext().unregisterReceiver(receiver);
    }

    @Override
    public void bindServiceFromPresenter(ServiceConnection serviceConnection, Intent intent) {
        getActivityContext().bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void unbindServiceFromPrsenter(ServiceConnection serviceConnection) {
        getActivityContext().unbindService(serviceConnection);
    }

    @Override
    public boolean showMsgDialog(String msg, String poText, String negaText, DialogInterface.OnClickListener positiveListener, DialogInterface.OnClickListener negativeListener) {
        if (getActivity() instanceof RoyBaseActivity)
            return ((RoyBaseActivity) getActivity()).showMsgDialog(msg, poText, negaText, positiveListener, negativeListener);
        return false;
    }

    @Override
    public boolean dismissMsgDialog() {
        if (getActivity() instanceof RoyBaseActivity)
            return ((RoyBaseActivity) getActivity()).dismissMsgDialog();
        return false;
    }

    protected void pushFragment(int containID, RoyBaseFragment fragment) {
        getHoldingActivity().pushFragment(containID, fragment);
    }

    protected void popFragment(RoyBaseFragment fragment) {
        getHoldingActivity().popFragment();
    }

    protected RoyBaseActivity getHoldingActivity() {
        if (getActivity() instanceof RoyBaseActivity) {
            return (RoyBaseActivity) getActivity();
        } else {
            throw new NoPatchException("获取HoldingActivity非继承RoyActivity");
        }
    }

    @Override
    public boolean showEditDialog(String title, String ediTextHint, DialogInterface.OnClickListener confirm, DialogInterface.OnClickListener cancel) {
        if (getActivity() instanceof RoyBaseActivity) {
            return ((RoyBaseActivity) getActivity()).showEditDialog(title, ediTextHint, confirm, cancel);
        }
        return false;
    }

    @Override
    public boolean dismissEditDialog() {
        if (getActivity() instanceof RoyBaseActivity) {
            return ((RoyBaseActivity) getActivity()).dismissEditDialog();
        }
        return false;
    }

    @Override
    public void reqGrantedPermission(String[] permission) {
        if (getActivity() instanceof RoyBaseActivity) {
            ((RoyBaseActivity) getActivity()).reqGrantedPermission(permission);
        }
    }

    @Override
    public void sendMessage2Application(int what) {
        sendMessage2Application(what, 0, 0, null);
    }

    @Override
    public void sendMessage2Application(int what, Bundle extraData) {
        sendMessage2Application(what, 0, 0, extraData);
    }

    @Override
    public void sendMessage2Application(int what, int arg1, int arg2) {
        sendMessage2Application(what, arg1, arg2, null);
    }

    @Override
    public void sendMessage2Application(int what, int arg1, int arg2, Bundle extraData) {
        if (getActivity() instanceof RoyBaseActivity) {
            ((RoyBaseActivity) getActivity()).sendMessage2Application(what, arg1, arg2, extraData);
        }
    }

    @Override
    public Application doGetApplication() {
        if (getActivity() instanceof RoyBaseActivity) {
            return ((RoyBaseActivity) getActivity()).doGetApplication();
        }
        return null;
    }
}
